<template>
  <div>
    <myDivider name="故障参数"></myDivider>
    <!-- <el-alert :closable="false" title="三级菜单1" type="success" /> -->
    <el-page-header @back="goBack" :content="this.operateType == 'update' ? '修改故障参数记录' : '新增故障参数记录'">
    </el-page-header>
    <div class="insert">


      <el-form ref="insertForm" :model="insertForm" label-width="80px" :inline="true" :rules="insertRules">

        <el-form-item label="记录名称:" :label-width="formLabelWidth" class="formItemStyle" prop="recordName">
          <el-input v-model="insertForm.recordName" autocomplete="off" style="width: 262px"></el-input>
        </el-form-item>

        <el-form-item label="设备位置:" :label-width="formLabelWidth" class="formItemStyle">
          <div class="block">
            <el-cascader v-model="insertForm.possitionIds" placeholder="试试搜索：1号仓库" :options="positionOptionsData"
              filterable @change="choosePosition"  ref="positionCascader"
              :props="{ checkStrictly: true, value: 'id', label: 'positionName' }" clearable style="width: 262px;">
            </el-cascader>
          </div>
        </el-form-item>


        <el-form-item label="关联设备:" :label-width="formLabelWidth" class="formItemStyle">
          <el-select v-model="insertForm.deviceId" placeholder="请搜索选择位置范围内的设备" style="width: 262px;" @focus="searchDevice">
            <el-option v-for="item in deviceOptionData" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="故障描述:" :label-width="formLabelWidth" class="formItemStyle">
          <el-input v-model="insertForm.description" autocomplete="off" style="width: 262px"></el-input>
        </el-form-item>



        <el-form-item label="参数详情:" :label-width="formLabelWidth" class="formItemStyle">
          <el-input v-model="insertForm.parameterDetail" autocomplete="off" style="width: 262px"></el-input>
        </el-form-item>


        <el-form-item label="记录时间:" :label-width="formLabelWidth" class="formItemStyle">
          <el-date-picker v-model="insertForm.recordTime" type="datetime" style=" width: 262px;" placeholder="记录时间">
          </el-date-picker>
        </el-form-item>



      </el-form>


    

      
      <el-form ref="form" :model="insertForm" label-width="80px" style="height: 41px;">
        <el-form-item style="float: right; margin-bottom: 80px;">
          <el-button type="primary" @click="onSubmitUpdate" v-if="this.operateType == 'update'">修改</el-button>
          <el-button type="primary" @click="onSubmit" v-if="this.operateType == 'insert'">添加</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
      <el-divider></el-divider>
      <!-- <div id="main" style="width: 600px;height:400px; margin-left: 280px;"> </div> -->
      <div id="main" :class="className" :style="{height:height,width:width}" ></div>
    </div>

    
  </div>
</template>

<style scoped>
.insert {
  margin-top: 90px;
  margin-left: 130px;
  height: 50%;
}

.menuTable {
  margin-top: 100px;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.menuTable .cell {
  text-align: center;
}

.findValue {
  width: 13%;
  margin-top: 20px;
  margin-left: 15px;
}

.operation {
  margin-right: 50px;
  float: right;
  margin-top: 20px;
}

.formStyle {
  width: 1300px;
  margin: 20px auto;
}

.formItemStyle {
  margin-bottom: 28px;
  margin-left: 22px;
}

.pageFooter {
  margin-top: 3%;
  margin-left: 40%;
}

.pageFooterFather {
  top: 84%;
  position: relative;
  width: 100%;
}

.el-cascader-menu {
  height: fit-content;
  width: fit-content;
}
</style>



<script>
import {
  getDeviceOptionsData,
  insertParameter,
  getPositionData,
  getParameterById,
  updateParameter,

} from "./parameter";
import * as echarts from "echarts";
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'

const animationDuration = 6000

const lineChartData = {
  newVisitis: {
    expectedData: [100, 120, 161, 134, 105, 160, 165],
    actualData: [120, 82, 91, 154, 162, 140, 145]
  }
}


export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    // chartData: {
    //   type: Object,
    //   required: true
    // }
  },
  data() {
    return {
      formLabelWidth: "120px", //控制前面label的宽度
      insertForm: {
        // 新增弹框参数
        recordName: "",
        recordTime: "",
        possitionIds: [],
        parameterDetail: "",
        description: "",
        state: "",
        deviceId:""

      },
      insertRules: {
        recordName: [
          {
            required: true,
            message: "记录名称不能为空",
            trigger: "blur",
          },
        ],
      },
      positionOptionsData: [],
      deviceOptionData: [],
      operateType: 'insert',
      deviceName: "",
      chart: null,


      
      
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },

  activated() {
    
    this.initChart()
    if (this.$route.query.operateType == 'update') {
      this.getParameterInfo(this.$route.query.id);
      this.operateType = 'update'
    } else {
      this.insertForm = {};
    }

  },
  
  mounted: function () {
    //初始化选项数据
    this.getPositionOptionsData();
    this.getDeviceOptions();
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {

    onSubmit() {

      this.$refs['insertForm'].validate((valid) => {})
      if (this.insertForm.recordName==undefined||this.insertForm.recordName=="" ) {
        return false;
      }
     
      insertParameter(this.insertForm).then((res) => {
        if (res.data.code == 200) {
          this.$message({
            message: '参数添加成功',
            type: 'success'
          });
          this.goBack();
        } else {
          this.$message({
            message: res.data.message,
            type: "warning",
          });
        }

      })

    },


    goBack() {
      this.$router.push({path: '/parameter/parameterManage'});
    },

    getPositionOptionsData() {
      getPositionData().then((res) => {
        this.positionOptionsData = res;
      })
    },
    getParameterInfo(id) {

      getParameterById(id).then((res) => {
        this.insertForm.recordName = res.recordName; 
        this.insertForm.possitionIds = res.positionId == 0 ? '' : eval('(' + res.positionIds + ')');
        this.insertForm.deviceId = res.deviceId;
        this.insertForm.description = res.description;
        this.insertForm.parameterDetail = res.parameterDetail;
        this.insertForm.recordTime = res.recordTime;
      })
    },

    getDeviceOptions() {


      //处理位置Id和分类Id两个参数
      if (this.insertForm.possitionIds != null && this.insertForm.possitionIds.length != 0) {
        this.insertForm.possition = this.insertForm.possitionIds[this.insertForm.possitionIds.length - 1];
      } else {
        this.insertForm.possition = 0
      }
      var positionId = this.insertForm.possition
      var name = this.insertForm.deviceName
      getDeviceOptionsData(positionId, name).then(res => {
        this.deviceOptionData = res.data
      })
    },
    choosePosition() {
      let node = this.$refs['positionCascader'].getCheckedNodes()

      if (node.length > 0) {

        this.insertForm.possition = node[0].value;

      }
    },

    searchDevice(){

      if (this.insertForm.possitionIds != null && this.insertForm.possitionIds.length != 0) {
        this.insertForm.possition = this.insertForm.possitionIds[this.insertForm.possitionIds.length - 1];
      } else {
        this.insertForm.possition = 0
      }
      var positionId = this.insertForm.possition
      var name = this.insertForm.deviceName
      getDeviceOptionsData(positionId, name).then(res => {
        this.deviceOptionData = res.data
      })
    },


    
    onSubmitUpdate() {

      this.insertForm.id = this.$route.query.id;
      this.$refs['insertForm'].validate((valid) => {})
      if (this.insertForm.recordName==undefined||this.insertForm.recordName=="" ||this.insertForm.id==undefined||this.insertForm.id=="") {
        return false;
      }
      updateParameter(this.insertForm).then((res) => {
        if (res.data.code == 200) {
          this.$message({
            message: '参数添加成功',
            type: 'success'
          });
          this.goBack();
        } else {
          this.$message({
            message: res.data.message,
            type: "warning",
          });
        }

      })
    },
    drawChart() {
        // 基于准备好的dom，初始化echarts实例  这个和上面的main对应
        let myChart = echarts.init(document.getElementById("main"));
        // 指定图表的配置项和数据
        let option = {
     
          tooltip: {},
          legend: {
            data: ["销量"],
          },
          xAxis: {
            type: 'category',
            data: ['A', 'B', 'C']
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              data: [120, 200, 150],
              type: 'line'
            }
          ],
        };
        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
      },

      initChart() {
      this.chart = echarts.init(document.getElementById("main"), 'macarons')
      this.setOptions(lineChartData.newVisitis);
      
    },
    setOptions({ expectedData, actualData } = {}) {
      this.chart.setOption({
        xAxis: {
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
          boundaryGap: false,
          axisTick: {
            show: false
          }
        },
        grid: {
          left: 10,
          right: 10,
          bottom: 20,
          top: 30,
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          padding: [5, 10]
        },
        yAxis: {
          axisTick: {
            show: false
          }
        },
        legend: {
          data: ['expected', 'actual']
        },
        series: [{
          name: 'expected', itemStyle: {
            normal: {
              color: '#FF005A',
              lineStyle: {
                color: '#FF005A',
                width: 2
              }
            }
          },
          smooth: true,
          type: 'line',
          data: expectedData,
          animationDuration: 2800,
          animationEasing: 'cubicInOut'
        },
        {
          name: 'actual',
          smooth: true,
          type: 'line',
          itemStyle: {
            normal: {
              color: '#3888fa',
              lineStyle: {
                color: '#3888fa',
                width: 2
              },
              areaStyle: {
                color: '#f3f8ff'
              }
            }
          },
          data: actualData,
          animationDuration: 2800,
          animationEasing: 'quadraticOut'
        }]
      })
    }
      
  },

  



};
</script>